package com.kyzh.core.pager.weal.video

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.gushenge.core.beans.Video
import com.gushenge.core.dao.MMKVConsts
import com.kyzh.core.R
import com.kyzh.core.adapters.VideoPagerAdapter
import com.kyzh.core.pager.weal.video.viewmodels.VideoBaseViewModel
import com.shuyu.gsyvideoplayer.GSYVideoManager
import kotlinx.android.synthetic.main.fragment_video_base.*


class VideoBaseFragment : Fragment() {

    val beans = mutableListOf<Video>()
    private var id = ""
    val viewModel by viewModels<VideoBaseViewModel>()

    private lateinit var  mPagerAdapter:VideoPagerAdapter
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_video_base, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

    private fun initData() {
        viewModel.getData()
        viewModel.beans.observe(viewLifecycleOwner){
            beans.addAll(it)
            mPagerAdapter.notifyDataSetChanged()
        }
    }

    private fun initView() {

        mPagerAdapter = VideoPagerAdapter(this, beans)
        viewPager2.adapter = mPagerAdapter
        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (position == beans.size - 1) {
                    viewModel.getData()
                    mPagerAdapter.notifyDataSetChanged()
                }
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                MMKVConsts.videoHidden = false
            }
        })
    }

    override fun onResume() {
        super.onResume()
        GSYVideoManager.onPause()
    }
}